package cn.iocoder.yudao.module.system.service.otherService;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.iocoder.yudao.module.system.controller.admin.otherService.vo.ApiCallCount;
import cn.iocoder.yudao.module.system.controller.admin.otherService.vo.EtlStatusVO;
import cn.iocoder.yudao.module.system.dal.mysql.otherService.ApiCallCountMapper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * @Description:
 * @Author: meiwanli
 * @Date: 2025-10-09 16:18
 */
@Service
@Slf4j
public class RecordQueryImpl implements RecordQuery{

    @Resource
    private ApiCallCountMapper apiCallCountMapper;


    private static final String VEHICLE_REPAIR_IP = "172.60.9.36:9077";
    private static final String WAYBILL_IP = "172.60.9.39:9077";

    // 常量定义
    private static final String DRIVER_INFO_URL = "http://172.60.9.39:8090/jks/port/getDriverInfo";
    private static final String VEHICLE_INFO_URL = "http://172.60.9.39:8090/jks/port/getVehicleInfo";
    private static final String SHIP_NOTE_URL = "http://172.60.9.39:8090/jks/port/getShippingNote";
    private static final String CAR_REPAIR_INFO = "http://172.60.9.36:9066/jks/car100/getCarRepairInfo";
    private static final String CONTENT_TYPE_JSON = "application/json";

    @Override
    public String getServiceLog(Integer serviceType) {
        try {
            String ipAndPort = getIpAndPortByServiceType(serviceType);
            if (ipAndPort == null) {
                log.warn("不支持的服务类型: {}", serviceType);
                return "不支持的服务类型";
            }

            log.info("获取{}日志", getServiceTypeName(serviceType));
            String url = "http://" + ipAndPort + "/jks/service/getLog";

            HttpResponse response = HttpRequest.post(url).execute();
            if (response.isOk()) {
                return response.body();
            } else {
                log.error("获取日志失败，服务类型: {}, 状态码: {}", serviceType, response.getStatus());
                return "获取日志失败，状态码: " + response.getStatus();
            }
        } catch (Exception e) {
            log.error("获取服务日志异常，服务类型: {}", serviceType, e);
            return "获取日志异常: " + e.getMessage();
        }
    }

    @Override
    public Boolean operationService(Integer serviceType, Integer operationType) {
        try {
            String ipAndPort = getIpAndPortByServiceType(serviceType);
            String urlSuffix = getUrlSuffixByOperationType(operationType);

            if (ipAndPort == null || urlSuffix == null) {
                log.warn("不支持的服务类型或操作类型: {}, {}", serviceType, operationType);
                return false;
            }

            log.info("{}{}", getServiceTypeName(serviceType), getOperationTypeName(operationType));
            String url = "http://" + ipAndPort + urlSuffix;



            HttpResponse response = HttpRequest.post(url).execute();
            boolean isSuccess = response.isOk();

            if (!isSuccess) {
                log.error("服务操作失败，服务类型: {}, 操作类型: {}, 状态码: {}",
                        serviceType, operationType, response.getStatus());
            }

            return isSuccess;
        } catch (Exception e) {
            log.error("服务操作异常，服务类型: {}, 操作类型: {}", serviceType, operationType, e);
            return false;
        }
    }

    /**
     * 测试司机信息查询服务接口连通性
     */
    @Override
    public Boolean testDriverInfoConn() {
        String jsonParams = "{\"qualificationNo\":\"410522198402174715\"}";
        return testServiceConnectivity(DRIVER_INFO_URL, jsonParams, "司机信息查询");
    }

    @Override
    public Boolean testVehicleInfoConn() {
        String jsonParams = "{\"vehicleNo\":\"新N54200\",\"vehiclePlateColor\":\"2\"}";
        return testServiceConnectivity(VEHICLE_INFO_URL, jsonParams, "车辆信息查询");
    }

    @Override
    public Boolean testShippingNoteConn() {
        String jsonParams = "{\"vehicleNo\":\"新N54200\",\"vehiclePlateColor\":\"2\"}";
        return testServiceConnectivity(SHIP_NOTE_URL, jsonParams, "运单信息查询");
    }

    @Override
    public Boolean testCarRepairInfoConn() {
        String jsonParams = "{\"vin\":\"LSGPC52U1DF157868\"}";
        return testServiceConnectivity(CAR_REPAIR_INFO, jsonParams, "车辆送修信息查询");
    }

    @Override
    public List<EtlStatusVO> getEtlStatus() {
        // 发送get请求 http://172.18.21.111:18081/api/getEtlStatus
        log.info("开始获取ETL服务状态");
        HttpResponse response = HttpRequest.get("http://172.18.21.111:18081/api/getEtlStatus")
                .execute();
        if (response.isOk()) {
            String body = response.body();
            // body转换成List<EtlStatusVO>
            return JSONObject.parseArray(body, EtlStatusVO.class);
        }else {
            log.error("获取ETL服务状态失败，状态码: {}", response.getStatus());
            return Collections.emptyList();
        }
    }

    @Override
    public void updateByStatisticalTime(ApiCallCount apiCallCount) {
        // 先根据统计时间查询是否存在记录
        ApiCallCount existingRecord = apiCallCountMapper.selectByStatisticalTime(apiCallCount.getStatisticalTime());

        if (existingRecord == null) {
            // 如果不存在，则插入新记录
            apiCallCountMapper.insert(apiCallCount);
        } else {
            // 如果存在，则更新记录
            apiCallCountMapper.updateByStatisticalTime(apiCallCount);
        }
    }

    @Override
    public List<ApiCallCount> getApiCallCount(Integer dayCount) {
        return apiCallCountMapper.selectApiCallCountList(dayCount);
    }

    /**
     * 测试服务连通性的通用方法
     * @param url 服务URL
     * @param jsonParams JSON参数
     * @param serviceName 服务名称（用于日志展示）
     * @return 连通性测试结果
     */
    private Boolean testServiceConnectivity(String url, String jsonParams, String serviceName) {
        try {
            log.info("开始测试{}服务连通性", serviceName);
            HttpResponse response = HttpRequest.post(url)
                    .header("Content-Type", CONTENT_TYPE_JSON)
                    .body(jsonParams)
                    .timeout(5000) // 设置超时时间
                    .execute();

            if (response.isOk()) {
                log.info("{}服务连通性测试成功", serviceName);
                return true;
            } else {
                log.error("测试{}服务连通性失败，状态码: {}", serviceName, response.getStatus());
                return false;
            }
        } catch (Exception e) {
            log.error("测试{}服务连通性异常", serviceName, e);
            return false;
        }
    }

    private String getIpAndPortByServiceType(Integer serviceType) {
        if (serviceType == 1) {
            return VEHICLE_REPAIR_IP;
        } else if (serviceType == 2) {
            return WAYBILL_IP;
        }
        return null;
    }

    /**
     * 根据操作类型获取对应的URL后缀
     * 1启动服务，2停止服务
     */
    private String getUrlSuffixByOperationType(Integer operationType) {
        if (operationType == 1) {
            return "/jks/service/startService";
        } else if (operationType == 2) {
            return "/jks/service/stopService";
        }
        return null;
    }

    /**
     * 根据服务类型获取对应的服务名称
     * 1车辆送修，2电子运单
     */
    private String getServiceTypeName(Integer serviceType) {
        if (serviceType == 1) {
            return "车辆送修";
        } else if (serviceType == 2) {
            return "电子运单";
        }
        return "未知服务";
    }

    private String getOperationTypeName(Integer operationType) {
        if (operationType == 1) {
            return "启动服务";
        } else if (operationType == 2) {
            return "停止服务";
        }
        return "未知操作";
    }
}

